<?php
/**************************************************************************
 * Naanal PHP Framework, Simple, Efficient and Developer Friendly
 * Ver 3.0, Copyright (C) <2010>  <Tamil Amuthan. R>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/
 
include_once dirname(__FILE__).'/constants.php';
include_once dirname(__FILE__).'/fileutils.php';
include_once dirname(__FILE__).'/databaseutils.php';

function getPagination($href,$totalItems,$currentPage=1,$itemsPerPage=20,$param="")
{
	$pagina=new PaginationUI($totalItems,$currentPage,$itemsPerPage);
	$pagina->paginationVar=ClsConfig::$PAGINATION_VAR;
	$prev=$pagina->getUIPrevLink($href,"Prev",$param);
	$next=$pagina->getUINextLink($href,"Next",$param);
	$first=$pagina->getUIFirstLink($href,"First",$param);
	$last=$pagina->getUILastLink($href,"Last",$param);
	$numPage=$pagina->getNumPage(); 
	$pagination=$first." ".$prev." "."(".$currentPage." of ".$numPage.")"." ".$next." ".$last;
	return $pagination;
}

function processEntry()
{
    $entry=ClsNaanalRequest::getInstance()->getData("entry");
    if($entry && file_exists("gate/{$entry}/entry.php"))
    {
        include_once("gate/{$entry}/entry.php");
    }
    else if(file_exists("gate/default/entry.php"))
    {
        include_once("gate/default/entry.php");
    }
    else
    {
        trace("Unstable installation"); 
    }
}
function processExit()
{
    $entry=ClsNaanalRequest::getInstance()->getData("entry");
    if($entry && file_exists("gate/{$entry}/exit.php"))
    {
        include_once("gate/{$entry}/exit.php");
    }
    else if(file_exists("gate/default/exit.php"))
    {
        include_once("gate/default/exit.php");
    }
}
function loadAppJS($source,$destination,$order=0)
{
    loadScriptFiles($source,$destination,"js",$order);
}
function loadAppCSS($source,$destination,$order=0)
{
    loadScriptFiles($source,$destination,"css",$order);
}
function loadAppImageFiles($fileName,$destination)
{
    $basename=basename($fileName);
    $session=  session_id();
    $dirname=  dirname(NAANAL_APP_PATH."naanal/".$destination);
    if(!file_exists($dirname))
    {
        mkdir($dirname, 0777, true);
    }
    if(ClsConfig::$isDeveloperMode)
    {
        copy($fileName,NAANAL_APP_PATH."naanal/".$destination);
    }
}
function loadScriptFiles($fileName,$destination,$fileType,$order=0)
{
    static $arrFile=array();
    if($fileName===false && $fileType===false) 
    {
        ksort($arrFile["js"],SORT_NUMERIC);
        ksort($arrFile["css"],SORT_NUMERIC);
        $arrFileNew=array();
        foreach($arrFile["js"] as $order=>$arrRow)
        {
            foreach($arrRow as $file)
            {
                if(in_array($file, $arrFileNew)) continue;
                $arrFileNew["js"][]=$file;
            }
        }
        foreach($arrFile["css"] as $order=>$arrRow)
        {
            foreach($arrRow as $file)
            {
                if(in_array($file, $arrFileNew)) continue;
                $arrFileNew["css"][]=$file;
            }
        }
        return $arrFileNew;
    }
    $basename=basename($fileName);
    $session=  session_id();
    $dirname=  dirname(NAANAL_APP_PATH."naanal/".$destination);
    if(!file_exists($dirname))
    {
        mkdir($dirname, 0777, true);
    }
    switch($fileType)
    {
        case "js":
        {
            if(ClsConfig::$isDeveloperMode || !file_exists(NAANAL_APP_PATH."naanal/".$destination))
            {
                copy($fileName,NAANAL_APP_PATH."naanal/".$destination);
            }
            $arrFile[$fileType][$order][]=NAANAL_WEB_PATH."naanal/{$destination}";
            break;
        }
        case "css":
        {
            if(ClsConfig::$isDeveloperMode || !file_exists(NAANAL_APP_PATH."naanal/".$destination))
            {
                copy($fileName,NAANAL_APP_PATH."naanal/".$destination);
            }
            $arrFile[$fileType][$order][]=NAANAL_WEB_PATH."naanal/{$destination}";
            break;
        }
    }
}
function isFrameworkInstalled()
{
    if(!file_exists("ClsConfig.php")) return false;
    include_once("ClsConfig.php");
    if(!class_exists("ClsConfig")) return false;
    $arrConfigVar=array("CONTROL_PANEL","LOG","LANG","isDeveloperMode","DATABASE","DISABLE_TRACKING","theme");
    foreach($arrConfigVar as $var)
    {
        if(!isset(ClsConfig::$$var)) return false;
    }
    return true;
}
function isApplicationInstalled()
{
    if(!file_exists("config.php")) 
    {
        return false;
    }
    
    foreach(ClsConfig::$CONFIG_VAR as $variable=>$arrInfo)
    {
        if(ClsConfig::$DATABASE_CONFIG_TYPE=="variable")
        {
            if(ClsNaanalConfigGen::getVarIndex($variable)==-1)
            {
                return false;
            }
        }
        else
        {
            if(ClsNaanalConfigGen::getDefineKeyIndex($variable)==-1)
            {
                return false;
            }
        }
    }
    /**
     * The application var must have some value other than default value
     */
    if(ClsConfig::$CONFIG_MANDATORY_VAR)
    foreach(ClsConfig::$CONFIG_MANDATORY_VAR as $applicationVar)
    {
        $dataIndex=ClsNaanalConfigGen::getDefineValueIndex($applicationVar);
        if(is_null($dataIndex) || $dataIndex==-1) 
        {
            return false;
        }
        $data=ClsNaanalConfigGen::extractValue($dataIndex);
        if(ClsConfig::$CONFIG_VAR[$applicationVar]["data"]===$data)
        {
            return false;
        }
        $configdata=ClsConfig::$CONFIG_VAR[$applicationVar]["data"];
    }
    $type=getAppConfig("DATABASE_CONFIG_TYPE");
    if($type=="constant")
    {
        include_once("config.php");
        $arrVar=get_defined_constants();
    }
    else
    {
        include("config.php");
        $arrVar=get_defined_vars();
    }
    /*$arrConfigVar=getAppConfig("CONFIG_VAR");
    if($arrConfigVar)
    foreach($arrConfigVar as $var)
    {
        $tmpvar=ClsConfig::$CONFIG_VAR_MAP[$var];
        if(!isset($arrVar[$tmpvar]))
        {
            return false;
        }
    }*/
    return true;
}
function &extractVariables($file)
{
    include $file;
    $arrVar=get_defined_vars();
    return $arrVar;
}
function getJSConfig($name)
{
    static $arrJSConfig=array();
    if(!isset($arrJSConfig[$name]))
    {
       $arrJSConfig[$name]=extractVariables(NAANAL_PATH."/js/{$name}/config.php");
    }
    return $arrJSConfig[$name];
}
function isEmptyString($data)
{
    $len=strlen($data);
    if($len===0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
function isNumericZero($data)
{
    if(strlen($data)===1 && strpos($data, "0")===0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
function addLog($message="None",$stepBack=0)
{
    static $objLog=null;
    ///if application is in install mode
    /*if(!class_exists("ClsConfig"))
    {
        if(is_null($objLog))
        {
            $objLog=new ClsLog();
        }
        $objLog->log($message,$stepBack);
    }
    else
    {
        if(IS_NAANAL_ADMIN===false && isset(ClsConfig::$LOG) && ClsConfig::$LOG===true)
        {
            if(is_null($objLog))
            {
                    $objLog=new ClsLog();
            }
            $objLog->log($message,$stepBack);
        }
    }*/
}
/**
 * gets application's config value.
 * @param type $name
 * @return if config exist, return data. else returns null
 */
function getAppConfig($name)
{
    if(!class_exists("ClsConfig")) return null;
    $configFile=isset(ClsConfig::$CONFIG_FILE)?ClsConfig::$CONFIG_FILE:"config.php";
    if(!file_exists($configFile))
    {
        return null;
    }
    if(ClsConfig::$DATABASE_CONFIG_TYPE=="variable")
    {
        if(file_exists($configFile))
        {
            include($configFile);
        }
        if(isset(ClsConfig::$CONFIG_VAR_MAP[$name]))
        {
            $name=ClsConfig::$CONFIG_VAR_MAP[$name];
        }
        if(isset($$name)) return $$name;
    }
    else if(ClsConfig::$DATABASE_CONFIG_TYPE=="constant")
    {
        include_once($configFile);
        if(isset(ClsConfig::$CONFIG_VAR_MAP[$name]))
        {
            $name=ClsConfig::$CONFIG_VAR_MAP[$name];
        }
        if(defined($name)) return constant($name);
    }
    if($name=="DATABASE")
    {
        if(isset(ClsConfig::$DATABASE))
        foreach(ClsConfig::$DATABASE as $database=>$arrData)
        {
            if($arrData["default"]===true) return $database;
        }
    }
    else if(isset(ClsConfig::$$name))
    {
        return ClsConfig::$$name;
    }
    return null;
    //trace("Application configuration '$name' not exist");exit;
}
function &getHook($hook)
{
    include("hooks.php");
    ///if database exist
    if(getAppConfig("DATABASE_NAME"))
    {
        $client_company=ClsNaanalSession::getInstance()->getPanelData("client_company");
        if($client_company)
        {
            include("client/{$client_company}/hooks.php");
            unset($client_company);
        }
    }
    if(isset($_REQUEST["module"]))
    {
        $naanal_module=$_REQUEST["module"];
    }
    else if(isset($_REQUEST["m"]))
    {
        $naanal_module=$_REQUEST["m"];
    }
    else
    {
        $naanal_module="home";
    }
    if(file_exists("modules/{$naanal_module}/hook.php"))
    {
        include("modules/{$naanal_module}/hook.php");
    }
    unset($naanal_module);
    $vars=get_defined_vars();
    
    if(array_key_exists($hook, $vars))
    {
        return $$hook;
    }
    else
    {
        $tmp=null;
        return $tmp;
    }
}
function getClientDirectory()
{
    static $path=null;
    if(is_null($path))
    {
        $client_id=ClsNaanalSession::getInstance()->getPanelData("client_id");
        $objClient=ClsWrapper::getInstance("client");
        $objClient->loadObject($client_id);
        $company=$objClient->get_company();
        $path="client/{$company}/";
    }
    return $path;
}
function getModuleList()
{
    static $arrModules=array();
    if(empty($arrModules))
    {
        if ($handle = opendir(NAANAL_APP_PATH."modules")) 
        {
            while ($fileName = readdir($handle))
            {
                if($fileName=="." || $fileName==".." || !is_dir(NAANAL_APP_PATH."modules/{$fileName}")) continue;
                $arrModules[] = $fileName;
            }
        }
    }
    return $arrModules;
}
function setGlobal($name,$data,$module=false,$action=false,$switch=false)
{
    ClsNaanalSession::getInstance()->setGlobal($name,$data,$module,$action,$switch);
}
function getGlobal($name,$module=false,$action=false,$switch=false)
{
    ClsNaanalSession::getInstance()->getGlobal($name,$module,$action,$switch);
}
function show_module($module,$action="create",$id=0,$arrParam=array(),$parentModule="",$parentAction="",$parentModuleID=0)
{
    $objLibModule=get_module_object($module,$action,$id,$arrParam,$parentModuleID,$parentAction,$parentModuleID);
    if($objLibModule===false) return false;
    echo $objLibModule->render();
}
function &get_module_content($module,$action="create",$id=0,$arrParam=array(),$parentModule="",$parentAction="",$parentModuleID=0)
{
    //$objLibModule=get_module_object($module,$action,$id,$arrParam,$parentModuleID,$parentAction,$parentModuleID);
    $objLibModule=get_module_object($module,$action,$id,$arrParam,$parentModuleID,$parentAction,$parentModuleID);
    if($objLibModule===false)
    {
        $ret=false;
        return $ret;
    }
    $content=$objLibModule->render();
    return $content;
}
function &get_module_object($module,$action="create",$id=0,$arrParam=array(),$parentModule="",$parentAction="",$parentModuleID=0,$table="")
{
    $objModule=new ClsNaanalModule($module,$action,$id);
    $isAuthenticationNeeded=$moduleLang=$objModule->getConfigVar("is_authentication_needed");
    
    if(is_null($isAuthenticationNeeded))
    {
         trace("configuration is_authentication_needed not set for module {$module}",null,false,true,false,false,  get_defined_vars());
    }
    if($isAuthenticationNeeded!==false)
    {
        if(!isLogged())
        {
            if($module=="home")
            {
                $loginPanel=getLoginControlPanel();
                $loginTable=ClsConfig::$CONTROL_PANEL[$loginPanel]["table"]["login"];
                $loginHomeModule=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["home"]["module"];
                $loginHomeAction=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["home"]["action"];
                $loginPage=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["module"];
                $loginAction=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["action"];
                $objModule=new ClsNaanalModule($loginPage,$loginAction,0);
                $module=$loginPage;
                $action=$loginAction;
                $table="";
                $id=0;
                $arrParam=array();
                $parentModule="";
                $parentAction="";
                $parentModuleID=0;
            }
            else
            {
                die("You are not authorized to view module: {$module}. Alternatively you can change the config value <b>is_authentication_needed</b> to false");
                $ret=false;
                return $ret;
            }
        }
    }
    $objModule->loadUtils();
    $objModule->isAutoSubmitButton=true;
    $objModule->parentModule=$parentModule;
    $objModule->parentAction=$parentAction;
    $objModule->parentModuleID=$parentModuleID;
    if($module=="appconfig" || $module=="install" || (IS_NAANAL_ADMIN===false && ClsConfig::$isDeveloperMode))
    {
        if($module!="modconfig") 
        {
            $success=$objModule->validate();
            if(!$success)
            {
                if($module=="appconfig") 
                {
                    die("Critical Error: Unstable Naanal Framework Installation");
                }
                else if($module=="install" && $objModule->isFrameworkModule()) 
                {
                    die("Critical Error: Unstable Naanal Framework Installation");
                }
                else
                {
                    $forValidate=$objModule->arrValidate;
                    $forArrConfigVar=$objModule->arrConfigVar;
                    $obj=  get_module_object("modconfig");
                    $obj->objParentModule=$objModule;
                    $obj->addAdditionalInput("forValidate",$forValidate);
                    $obj->addAdditionalInput("forConfigVar",$forArrConfigVar);
                    $objModule=$obj;
                }
            }
        }
    }
    $moduleLang=$objModule->getConfigVar("lang");
    $configTable=$objModule->getConfigVar("table");
    if(is_null($configTable) && $table!=="")
    {
        $objModule->setConfigTable($table);
    }
    $objModule->addAdditionalInput("params",$arrParam);
    if($moduleLang===true)
    {
        $moduleLang=ClsConfig::$LANG;
    }
    if(!empty($moduleLang))
    {
        $objModule->loadLanguage($moduleLang);
    }
    return $objModule;
    /*$objLibModule=new ClsNaanalModule($module,$action,$id,$arrParam,$parentModuleID,$parentAction,$parentModuleID);
    $objLibModule->controlpanel= getCurrentControlPanel();
    $objLibModule->isAutoSubmitButton=true;
    $objLibModule->parentModule=$parentModule;
    $objLibModule->parentAction=$parentAction;
    $objLibModule->parentModuleID=$parentModuleID;
    $success=$objLibModule->validate();
    if(!$success)
    {
        if(!ClsConfig::$isDeveloperMode)
        {
            return false;
        }
        if($module=="appconfig" || $module=="modconfig") return false;
        $id=0;
        $objConfiggenModule=new ClsNaanalModule("modconfig","create",$id);

        $objConfiggenModule->objParentModule=$objLibModule;
        $objConfiggenModule->addAdditionalInput("forValidate",$objLibModule->arrValidate);
        $objConfiggenModule->addAdditionalInput("forArrConfigVar",$objLibModule->arrConfigVar);

        $objConfiggenModule->loadUtils();
        $objConfiggenModule->controlpanel="guest";
        $objConfiggenModule->homepage="index.php";
        $configgenSuccess=$objConfiggenModule->validate();
        if(!$configgenSuccess)
        {
            if(isset($objConfiggenModule->arrValidate["config"])&& $objConfiggenModule->arrValidate["config"]===false)
            {
                die("Critical Error: Unstable Naanal Framework Installation");
            }
        }
        return $objConfiggenModule;
        //$out=$objConfiggenModule->render();
        //$moduleTheme=$objConfiggenModule->getConfigVar("theme");
    }
    $objLibModule->loadUtils();
    $objLibModule->homepage="index.php";
    return $objLibModule;*/
}
//Function to seperate multiple tags one line
function fix_newlines_for_clean_html($fixthistext)
{
	$fixthistext_array = explode("\n", $fixthistext);
	foreach ($fixthistext_array as $unfixedtextkey => $unfixedtextvalue)
	{
		//Makes sure empty lines are ignores
		if (!preg_match("/^(\s)*$/", $unfixedtextvalue))
		{
			$fixedtextvalue = preg_replace("/>(\s|\t)*</U", ">\n<", $unfixedtextvalue);
			$fixedtext_array[$unfixedtextkey] = $fixedtextvalue;
		}
	}
	return implode("\n", $fixedtext_array);
}
function getConfigVar($variable)
{
    static $arrConfigVar=array();
    if(!isset($arrConfigVar[$variable]))
    {
        if(!file_exists("ClsConfig.php")) return null;
        if(!class_exists("ClsConfig")) return null;
        if(!isset(ClsConfig::$$variable)) return null;
        $arrConfigVar[$variable]=ClsConfig::$$variable;
    }
    return $arrConfigVar[$variable];
}
function getEntryPoint()
{
    $entry=ClsNaanalSession::getInstance()->getData("entry");
    if(empty($entry))
    {
        if(file_exists("gate/default"))
        {
            return "default";
        }
        else
        {
            return false;
        }
    }
    else
    {
        if(file_exists("gate/{$entry}"))
        {
            return $entry;
        }
        else
        {
            return false;
        }
    }
}
function isExtensionLoaded($phpExtension)
{
    if (extension_loaded($phpExtension))
    {
        return true;
    }
    return false;
}
function clean_html_code($uncleanhtml)
{
	//Set wanted indentation
	$indent = "    ";


	//Uses previous function to seperate tags
	$fixed_uncleanhtml = fix_newlines_for_clean_html($uncleanhtml);
	$uncleanhtml_array = explode("\n", $fixed_uncleanhtml);
	//Sets no indentation
	$indentlevel = 0;
	foreach ($uncleanhtml_array as $uncleanhtml_key => $currentuncleanhtml)
	{
		//Removes all indentation
		$currentuncleanhtml = preg_replace("/\t+/", "", $currentuncleanhtml);
		$currentuncleanhtml = preg_replace("/^\s+/", "", $currentuncleanhtml);

		$replaceindent = "";

		//Sets the indentation from current indentlevel
		for ($o = 0; $o < $indentlevel; $o++)
		{
			$replaceindent .= $indent;
		}

		//If self-closing tag, simply apply indent
		if (preg_match("/<(.+)\/>/", $currentuncleanhtml))
		{
			$cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
		}
		//If doctype declaration, simply apply indent
		else if (preg_match("/<!(.*)>/", $currentuncleanhtml))
		{
			$cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
		}
		//If opening AND closing tag on same line, simply apply indent
		else if (preg_match("/<[^\/](.*)>/", $currentuncleanhtml) && preg_match("/<\/(.*)>/", $currentuncleanhtml))
		{
			$cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
		}
		//If closing HTML tag or closing JavaScript clams, decrease indentation and then apply the new level
		else if (preg_match("/<\/(.*)>/", $currentuncleanhtml) || preg_match("/^(\s|\t)*\}{1}(\s|\t)*$/", $currentuncleanhtml))
		{
			$indentlevel--;
			$replaceindent = "";
			for ($o = 0; $o < $indentlevel; $o++)
			{
				$replaceindent .= $indent;
			}

			$cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;
		}
		//If opening HTML tag AND not a stand-alone tag, or opening JavaScript clams, increase indentation and then apply new level
		else if ((preg_match("/<[^\/](.*)>/", $currentuncleanhtml) && !preg_match("/<(link|meta|base|br|img|hr)(.*)>/", $currentuncleanhtml)) || preg_match("/^(\s|\t)*\{{1}(\s|\t)*$/", $currentuncleanhtml))
		{
			$cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;

			$indentlevel++;
			$replaceindent = "";
			for ($o = 0; $o < $indentlevel; $o++)
			{
				$replaceindent .= $indent;
			}
		}
		else
		//Else, only apply indentation
		{$cleanhtml_array[$uncleanhtml_key] = $replaceindent.$currentuncleanhtml;}
	}
	//Return single string seperated by newline
	return implode("\n", $cleanhtml_array);
}
/**
 * 
 * checks the mysql server and show whether the database exist or not
 * if parameter is id, the name is derived from database table, and verify it against database
 * @param string(if the paramer is database name) or number(if the parameter is database id) $db
 * @param boolean $isDatabaseID
 */
function isDatabaseExist($db,$isDatabaseID=false)
{
	if($isDatabaseID)
	{
		$pdo=ClsNaanalPDO::getNamedInstance("tmp");
		$pdo->setQuery("select * from `database` where id={$db}");
		$arr=$pdo->getAllAssoc();
		$db=$arr[0]["databasename"];
	}
	$sql="select * from information_schema.SCHEMATA where `SCHEMA_NAME`='{$db}'";
	$pdo=ClsNaanalPDO::getNamedInstance("meta",false);
	$pdo->setQuery($sql);
	$arr=$pdo->getAllAssoc();
	if(isset($arr[0]["SCHEMA_NAME"])) return true;
	else return false;
} 
function cleanDBValue($value)
{
	return addslashes($value);
}
function getNthPath($stepBack=0)
{
	$arr=debug_backtrace();
	$file=isset($arr[1+$stepBack]["file"])?$arr[1+$stepBack]["file"]:"";
	return $file;
}
function getGISDistance($latitude,$longitude,$latitude1,$longitude1)
{
	if(empty($latitude)) $latitude=0;
	if(empty($longitude)) $longitude=0;
	if(empty($lattitude1)) $lattitude1=0;
	if(empty($longitude1)) $longitude1=0;
	///search comps based on radius
	$R=6371;
	$dLat=(atan(1)/45*($latitude1-$latitude));
	/*COMPUTING THE DLAT BY CONSIDERING THE (SUB_LAT-COMPS_LAT)*/
	$dLon=(atan(1)/45*($longitude1-$longitude));
	/*COMPUTING THE DLON BY CONSIDERING THE (SUB_LON-COMPS_LON)*/
	$a = sin($dLat/2) * sin($dLat/2) + cos((atan(1)/45*$latitude)) * cos((atan(1)/45*$latitude1)) * sin($dLon/2) * sin($dLon/2);
	$c = 2 * atan2(sqrt($a), sqrt(1-$a));
	$d = $R * $c ;//trace($d);
	$DISTANCE = $d *0.621371192;
	return $DISTANCE;
}

function get_recursive($dir,$call_func,$basepath=false) {
$dir=  trim($dir, "/\\");
$basepath=$basepath?$basepath:$dir;
$files = scandir($dir);
array_shift($files);    // remove '.' from array
array_shift($files);    // remove '..' from array
foreach ($files as $file) {
    $file = $dir . '/' . $file;
    if (is_dir($file)) {
        get_recursive($file,$call_func,$basepath);
    } else {
        $realPath=  realpath($file);
        $basepath=  realpath($basepath);
        $call_func($file,$basepath);
    }
}
}

function rmdir_recursive($dir) {
    $files = scandir($dir);
    array_shift($files);    // remove '.' from array
    array_shift($files);    // remove '..' from array
    foreach ($files as $file) {
        $file = $dir . '/' . $file;
        if (is_dir($file)) {
            rmdir_recursive($file);
            rmdir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dir);
}
function getControlPanelConfig($key)
{
	static $objConfig=null;
	if(is_null($objConfig)) $objConfig = new __Config("controlpanel.ini"); 
	$data=$objConfig->pString($key);
	if($data=="true") return true;
	else if($data=="false") return false;
	else return $data;	
}

function getDynamicDatabase()
{
    $objSession=  ClsNaanalSession::getInstance();
    $compsdatabase=$objSession->getPanelData("compsdatabase") ? $objSession->getPanelData("compsdatabase") : $objSession->getPanelData("dynamicdatabase");
    $loginPanel=$objSession->getData("loginpanel");

    if(!empty($compsdatabase))
    {
        $sql="select * from `database` where `id`=".$compsdatabase;
        $pdo=ClsLPDO::getNamedInstance();
        $pdo->setQuery($sql);
        $arrAssoc=$pdo->getAllAssoc();
        $database=$arrAssoc[0]["databasename"];
        return $database;
    }
    else 
    {
        return false;
    }
}

function sendFileAttachment($from,$to,$subject,$msg,$attachment,$filename="")
{
	$filename=empty($filename)?basename($attachment):$filename;
	require_once(dirname(__FILE__)."/mimemessage/email_message.php");
/*
 *  Trying to guess your e-mail address.
 *  It is better that you change this line to your address explicitly.
 *  $from_address="me@mydomain.com";
 *  $from_name="My Name";
*/
	//$from_address=getenv("USER")."@".getenv("HOSTNAME");
	$from_address=$from;
	$from_name=getenv("USERNAME");
	//$from_name="Tamil Amuthan";

	$reply_name=$from_name;
	$reply_address=$from_address;
	$reply_address=$from_address;
	$error_delivery_name=$from_name;
	$error_delivery_address=$from_address;

/*
 *  Change these lines or else you will be mailing the class author.
 */
	$to_name=$to;
	$to_address=$to;

	$email_message=new email_message_class;
	$email_message->SetEncodedEmailHeader("To",$to_address,$to_name);
	$email_message->SetEncodedEmailHeader("From",$from_address,$from_name);
	$email_message->SetEncodedEmailHeader("Reply-To",$reply_address,$reply_name);
	$email_message->SetHeader("Sender",$from_address);

/*
 *  Set the Return-Path header to define the envelope sender address to which bounced messages are delivered.
 *  If you are using Windows, you need to use the smtp_message_class to set the return-path address.
 */
	if(defined("PHP_OS")
	&& strcmp(substr(PHP_OS,0,3),"WIN"))
		$email_message->SetHeader("Return-Path",$error_delivery_address);

	$email_message->SetEncodedHeader("Subject",$subject);

/*
 *  A message with attached files usually has a text message part
 *  followed by one or more attached file parts.
 */
	$text_message=$msg;
	$email_message->AddQuotedPrintableTextPart($email_message->WrapText($text_message));

	/*$text_attachment=array(
		"Data"=>$attachment,
		"Name"=>empty($filename)?"attachment.txt":$filename,
		"Content-Type"=>"automatic/name",
		"Disposition"=>"attachment"
	);
	$email_message->AddFilePart($text_attachment);*/

	$image_attachment=array(
		"FileName"=>$filename,
		"Content-Type"=>"automatic/name",
		"Disposition"=>"attachment"
	);
	$email_message->AddFilePart($image_attachment);

/*
 *  The message is now ready to be assembled and sent.
 *  Notice that most of the functions used before this point may fail due to
 *  programming errors in your script. You may safely ignore any errors until
 *  the message is sent to not bloat your scripts with too much error checking.
 */
	$error=$email_message->Send();
	if(strcmp($error,""))
		return $error;
	else
		echo true;
}

function sendTextAttachment($from,$to,$subject,$msg,$attachment,$filename="")
{
	require_once(dirname(__FILE__)."/email_message.php");
/*
 *  Trying to guess your e-mail address.
 *  It is better that you change this line to your address explicitly.
 *  $from_address="me@mydomain.com";
 *  $from_name="My Name";
*/
	//$from_address=getenv("USER")."@".getenv("HOSTNAME");
	$from_address=$from;
	$from_name=getenv("USERNAME");
	//$from_name="Tamil Amuthan";

	$reply_name=$from_name;
	$reply_address=$from_address;
	$reply_address=$from_address;
	$error_delivery_name=$from_name;
	$error_delivery_address=$from_address;

/*
 *  Change these lines or else you will be mailing the class author.
 */
	$to_name=$to;
	$to_address=$to;

	$email_message=new email_message_class;
	$email_message->SetEncodedEmailHeader("To",$to_address,$to_name);
	$email_message->SetEncodedEmailHeader("From",$from_address,$from_name);
	$email_message->SetEncodedEmailHeader("Reply-To",$reply_address,$reply_name);
	$email_message->SetHeader("Sender",$from_address);

/*
 *  Set the Return-Path header to define the envelope sender address to which bounced messages are delivered.
 *  If you are using Windows, you need to use the smtp_message_class to set the return-path address.
 */
	if(defined("PHP_OS")
	&& strcmp(substr(PHP_OS,0,3),"WIN"))
		$email_message->SetHeader("Return-Path",$error_delivery_address);

	$email_message->SetEncodedHeader("Subject",$subject);

/*
 *  A message with attached files usually has a text message part
 *  followed by one or more attached file parts.
 */
	$text_message=$msg;
	$email_message->AddQuotedPrintableTextPart($email_message->WrapText($text_message));

	$text_attachment=array(
		"Data"=>$attachment,
		"Name"=>empty($filename)?"attachment.txt":$filename,
		"Content-Type"=>"automatic/name",
		"Disposition"=>"attachment"
	);
	$email_message->AddFilePart($text_attachment);

	/*$image_attachment=array(
		"FileName"=>"http://www.phpclasses.org/graphics/logo.gif",
		"Content-Type"=>"automatic/name",
		"Disposition"=>"attachment"
	);
	$email_message->AddFilePart($image_attachment);*/

/*
 *  The message is now ready to be assembled and sent.
 *  Notice that most of the functions used before this point may fail due to
 *  programming errors in your script. You may safely ignore any errors until
 *  the message is sent to not bloat your scripts with too much error checking.
 */
	$error=$email_message->Send();
	if(strcmp($error,""))
		return $error;
	else
		echo true;
}
function exportToExcel($sql)
{
  // Connect database.
  //mysql_connect("localhost","jobonhand","ramesh");
  //mysql_select_db("db_resume");
  
  // Get data records from table.
  $result=mysql_query($sql);
  
  // Functions for export to excel.
  function xlsBOF() 
  {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
  }
  function xlsEOF() 
  {
    echo pack("ss", 0x0A, 0x00);
    return;
  }
  function xlsWriteNumber($Row, $Col, $Value) 
  {
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
    echo pack("d", $Value);
    return;
  }
  function xlsWriteLabel($Row, $Col, $Value ) 
  {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
  }
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Content-Type: application/force-download");
  header("Content-Type: application/octet-stream");
  header("Content-Type: application/download");;
  header("Content-Disposition: attachment;filename=resumelist.xls ");
  header("Content-Transfer-Encoding: binary ");
  
  xlsBOF();
  
  /*
  Make a top line on your excel sheet at line 1 (starting at 0).
  The first number is the row number and the second number is the column, both are start at '0'
  */
  
  //xlsWriteLabel(0,0,"List of car company.");
  
  // Make column labels. (at line 3)
  //xlsWriteLabel(2,0,"No.");
  //xlsWriteLabel(2,1,"Company");
  
  $xlsRow = 3;
  
  $isHeading=true;
  
  // Put data records from mysql by while loop.
  while($row=mysql_fetch_assoc($result))
  {
    if($isHeading)
    {
      $h=0;
      foreach($row as $fld=>$va)
      {
        if($fld=="id") 
        {
          xlsWriteLabel($xlsRow,$h++,"View Resume");
        }
        else
          xlsWriteLabel($xlsRow,$h++,trim($fld));
      }
      $isHeading=false;
      $xlsRow++;
    }
    $m=0;
    foreach($row as $fld=>$va)
    {
      if($fld=="id")
      {
        //$tmpva="http://www.jobonhand.com/job/admin/index.php?unipage=showresumelist_old&action=preview&id=".$row["id"];
        xlsWriteLabel($xlsRow,$m++,trim($va));
      }
      else
      {
      	$va=addslashes($va);
        xlsWriteLabel($xlsRow,$m++,trim($va));
      }
    }
    $xlsRow++;
  }
  xlsEOF();
}
function errMsg($errcode=null)
{
    $objNaanalSession=  ClsNaanalSession::getInstance();
    static $code="";
    if(IS_NAANAL_ADMIN===false && is_null($errcode))
    {
        $config = new __Config("err.ini");
        $err="";
        if(empty($code))
        {
        }
        else
        {
            if($config->isConfigExist($code))
            {
                $err=$config->pString($code);
            }
            else 
            {
                $err=$code;
            }
        }
        if($objNaanalSession->isPanelDataSet("err")) $objNaanalSession->deletePanelData("err");
        return $err;
    }
    else
    {
            addLog($errcode,1);
            $code=$errcode;
            ///store error code for later retrieval if the user redirects the page
            $objNaanalSession->setPanelData("err",$code);
    }
}
function getRandomString($length,$randword=null)
{
	$pass=(string)rand(161141, 999999);
	$randword=is_null($randword)?"sd#&^uiv12389":$randword;
	$randlen=strlen($randword);
	$newpass="";
	for($i=0;$i<$length;$i++)
	{
		$pos=rand(0, $randlen-1);
		$newpass.=$randword[$pos];	
	}
	return $newpass;
}
function getStatisticsData($array, $output = 'mean')
{
    if(!is_array($array))
    {
        return FALSE;
    }
    else
    {
        switch($output)
        {
            case 'mean':
                $count = count($array);
                $sum = array_sum($array);
                $total = $sum / $count;
            break;
            case 'median':
                rsort($array);
                $middle = round(count($array) / 2);
                $total = $array[$middle-1];
            break;
            case 'mode':
                $v = array_count_values($array);
                arsort($v);
                foreach($v as $k => $v){$total = $k; break;}
            break;
            case 'range':
                sort($array);
                $sml = $array[0];
                rsort($array);
                $lrg = $array[0];
                $total = $lrg - $sml;
            break;
        }
        return $total;
    }
}
function getRowMedian($arr) {
    sort($arr);
    $count = count($arr); //total numbers in array
    $middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
    if($count % 2) { // odd number, middle is the median
        $median = $arr[$middleval];
    } else { // even number, calculate avg of 2 medians
        $low = $arr[$middleval];
        $high = $arr[$middleval+1];
        $median = (($low+$high)/2);
    }
    return $median;
}

function getRowAverage($arr) {
    $count = count($arr); //total numbers in array
    $total=0;
    foreach ($arr as $value) {
        $total = $total + $value; // total value of array numbers
    }
    $average = ($total/$count); // get average value
    return $average;
}

function getDateDropdown($name,$defaultDate=0)
{
	$date="<select name='{$name}'>
	<option value='0'>- Select -</option>
	";
	for($i=1;$i<31;$i++)
	{
		if($i==$defaultDate)
		$date=$date."<option selected='selected' value='{$i}'>{$i}</option>
		";	
		else
		$date=$date."<option  value='{$i}'>{$i}</option>
		";
	}
	return $date;
}

function getMonthDropdown($name,$defaultMonth=0)
{
	$arrMonth=array("Jan","Feb","Mar","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	$month="<select name='{$name}'>
	<option value='0'>- Select -</option>
	";
	for($i=1;$i<12;$i++)
	{
		if($i==$defaultMonth)
		$month=$month."<option selected='selected' value='{$i}'>{$arrMonth[$i-1]}</option>
		";
		else
		$month=$month."<option  value='{$i}'>{$arrMonth[$i-1]}</option>
		";
	}
	return $month;
}

function evaluateFormula($formula,$arrData)
{
    if(strpos($formula, '<?')!==false)
    {
        return false;
    }
    if(strpos($formula, '<?php')!==false)
    {
        return false;
    }
    if(strpos($formula, '?>')!==false)
    {
        return false;
    }
    $arrAllowedToken=array(367,368,305,307,370,371,306,369,315);
    $arrToken=token_get_all('<?php '.$formula.' ?>');
    $arrNewToken=array();
    foreach($arrToken as $token)
    {
        if(is_array($token) && !in_array($token[0],$arrAllowedToken))
        {
            return false;
        }
    }
    $arrPreg=  preg_match_all("/{[^{\n\t\s\r]*}/", $formula, $arrTmp);
    $arrTpl=$arrTmp[0];
    foreach($arrTpl as $tpl)
    {
        $trim_tpl=trim($tpl,'{}');
        $formula=str_replace($tpl, $arrData[$trim_tpl],$formula);
    }
    ob_start();
    eval('$calc_val='.$formula.';');
    $error=  ob_get_clean();
    if($error) return false;
    else return $calc_val;
    //return isset($calc_val) && $calc_val!==false ? $calc_val: false;
}

///suitable for multiple file upload. this function converts multiple file column format to row format
///suitable for naming array in mulitple insert form
function convertColumnwiseToRowwise($arrRequestColumn,$isAssociateArray=false)
{
	$arrRow=array();
	$arrColumn=array();
	$arrHead=array();
	if($arrRequestColumn)
	foreach($arrRequestColumn as $columname=>$arrCol)
	{
		$arrColumn=$arrCol;
		$arrHead[]=$columname;
	}
	if(!$isAssociateArray) $arrRow[0]=$arrHead;
	$count=count($arrColumn);
	if($arrColumn)
	foreach($arrColumn as $k=>$v)
	{
		foreach($arrHead as $head)
		{
			if($isAssociateArray) $arrRow[$k][$head]=$arrRequestColumn[$head][$k];
			else $arrRow[$k][]=$arrRequestColumn[$head][$k];	
		}
	}
	return $arrRow;
} 

function uniqueName() 
{
	// explode the IP of the remote client into four parts
	$arrIp = explode('.', $_SERVER['REMOTE_ADDR']);
	// get both seconds and microseconds parts of the time
	list($usec, $sec) = explode(' ', microtime());
	// fudge the time we just got to create two 16 bit words
	$usec = (integer) ($usec * 65536);
	$sec = ((integer) $sec) & 0xFFFF;
	// fun bit--convert the remote client's IP into a 32 bit
	// hex number then tag on the time.
	// Result of this operation looks like this xxxxxxxx-xxxx-xxxx
	$strUid = sprintf("%08x_%04x_%04x", ($arrIp[0] << 24) | ($arrIp[1] << 16) | ($arrIp[2] << 8) | $arrIp[3], $sec, $usec);
	// tack on the extension and return the filename
	return $strUid;
}

function strToPrice($price)
{        
  $num="";
  for($i=0;$i<strlen($price);$i++)
  {
    if($price[$i]=="," || $price[$i]==" ") continue;
    $num=$num.$price[$i];    
  }
  return $num;
}
function isFieldExist($database,$table,$field)
{
    $arrField=getTableFields($database,$table);
    if(!empty($arrField) && in_array($field, $arrField))
    {
        return true;
    }
    return false;
}
function &getTableFields($database,$table,$usePDO=true)
{
	static $arrFields=array();
	if(!isset($arrFields[$database][$table]))
	{
            $sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{$database}' AND TABLE_NAME = '$table'";
            $pdo=ClsNaanalPDO::getNamedInstance("INFORMATION_SCHEMA");
            $pdo->setQuery($sql);  
            $arrFields[$database][$table]=$pdo->getColumn("COLUMN_NAME");
	}
	return $arrFields[$database][$table];
}
function getForignTable($database,$table,$field)
{
	$sql="select REFERENCED_TABLE_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{$database}' AND TABLE_NAME='{$table}' AND COLUMN_NAME='{$field}'";
	$pdo=ClsNaanalPDO::getNamedInstance("INFORMATION_SCHEMA");
	$pdo->setQuery($sql);
	$arr=$pdo->getAllRow();
	if(isset($arr[0])) return $arr[0];
	else return false;
}
function isTableExist($database,$table)
{
	$sql="SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='{$database}' AND TABLE_NAME='{$table}'";
	//trace($sql); 
	$pdo=ClsNaanalPDO::getNamedInstance("INFORMATION_SCHEMA");
	$pdo->setQuery($sql);
	$arr=$pdo->getAllRow();
        if($arr===false)
        {
            trace($pdo->getError());
            return false;
        }
	if(isset($arr[0])) return true;
	else return false;
}
/*
 * $name = name to be prefixed for column index
 * $list = list of row
 * $cols = number of column to be converted
 */
function getMultiColumn($list,$cols,$name="")
{
	$firstdim=-1;
	$i=0;
	$arrMultiColulmn=array();
	if($list)
	foreach($list as $ind=>$row)
	{
		$i=$ind % $cols;
		if($i === 0)
		{
			$firstdim=$firstdim+1;
		}
		$arrMultiColulmn[$firstdim][$name.$i]=$row;
	}
	return $arrMultiColulmn;
}
function getForiegnKeys($database,$table)
{
	$sql="select distinct
    table_name,column_name,referenced_table_name,referenced_column_name 
from
    information_schema.key_column_usage
where
    referenced_table_name is not null and table_name='{$table}' and TABLE_SCHEMA='{$database}';";
	$pdo=ClsNaanalPDO::getNamedInstance("INFORMATION_SCHEMA");
        if(get_class($pdo)!="ClsNaanalPDO") traceDirect($pdo);
	$pdo->setQuery($sql);
	$arrRow=$pdo->getAllAssoc();
	$arrKey=array();
	if($arrRow)
	foreach($arrRow as $row)
	{
		$arrKey[$row["column_name"]]=array("table"=>$row["referenced_table_name"],"field"=>"referenced_column_name");
	}
	return $arrKey;
}
/**
 * get current full url
 */
function getCurrentURL()
{
	if(!isset($_SERVER['REQUEST_URI']))
	{ 
		$serverrequri = $_SERVER['PHP_SELF']; 
	}
	else
	{ 
		$serverrequri = $_SERVER['REQUEST_URI']; 
	}
	$s = !isset($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$pos=strpos($_SERVER["SERVER_PROTOCOL"], "/");
	$servprotocol=substr($_SERVER["SERVER_PROTOCOL"], 0,$pos);
	$protocol = strtolower($servprotocol).$s; 
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); 
    return $protocol."://".$_SERVER['SERVER_NAME'].$port.$serverrequri; 
}

function priceToStr($price,$isIndianStandard=true)
{
  $arrPrice=explode(".",$price);        
  $num=$arrPrice[0];
  $paisa=isset($arrPrice[1])?".".$arrPrice[1]:"";
  
  if($num[0]=="-" || $num[0]=="+")
  {
      $sign = $num[0];
      $num=  substr($num, 1);
  }
  else
  {
      $sign = "";
  }
  
  $arrCommaIndia=array(3,5,7,9,11);
  $arrCommaUS=array(3,6,9,12);
  $str="";
  $lennum=strlen($num);
  for($i=0;$i<$lennum;$i++)
  {
    if($isIndianStandard) 
    {
      if(in_array($lennum-$i,$arrCommaIndia)) $str.=",";// continue;
    }
    else
    {
      if(in_array($lennum-$i,$arrCommaUS)) $str.=",";// continue;
    }
    $str=$str.$num[$i];    
  }
  $str=trim($str,", ");
  $str=trim($str,", ");
  return $sign.$str.$paisa;
}

function number_to_words ($x,$isIndianStandard=true)
{
     $nwords = array(  "", "one", "two", "three", "four", "five", "six", 
	      	  "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", 
	      	  "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", 
	     	  "nineteen", "twenty", 30 => "thirty", 40 => "fourty",
                     50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eigthy",
                     90 => "ninety" );
     if(!is_numeric($x))
     {
         $w = '#';
     }
     else if(fmod($x, 1) != 0)
     {
         $w = '#';
     }
     else
     {
         if($x < 0)
         {
             $w = 'minus ';
             $x = -$x;
         }
         else
         {
             $w = '';
         }
         if($x < 21)
         {
             $w .= $nwords[$x];
         }
         else if($x < 100)
         {
             $w .= $nwords[10 * floor($x/10)];
             $r = fmod($x, 10);
             if($r > 0)
             {
                 $w .= ' '. $nwords[$r];
             }
         } else if($x < 1000)
         {
		
             	$w .= $nwords[floor($x/100)] .' hundred';
             $r = fmod($x, 100);
             if($r > 0)
             {
                 $w .= ' '. number_to_words($r);
             }
         } 
         else
         {
           if($isIndianStandard)
           { 
             if($x < 100000)
             {
             	$w .= number_to_words(floor($x/1000)) .' thousand';
                 $r = fmod($x, 1000);
                 if($r > 0)
                 {
                     $w .= ' ';
                     if($r < 100)
                     {
                         $w .= ' ';
                     }
                     $w .= number_to_words($r);
                 }
             }
             else if($x < 10000000)
             {
             	$w .= number_to_words(floor($x/100000)) .' lakhs';
                 $r = fmod($x, 1000);
                 if($r > 0)
                 {
                     $w .= ' ';
                     if($r < 100)
                     {
                         $w .= ' ';
                     }
                     $w .= number_to_words($r);
                 }
             } 
             else 
             {
                 $w .= number_to_words(floor($x/10000000)) .' crore';
                 $r = fmod($x, 1000000);
                 if($r > 0)
                 {
                     $w .= ' ';
                     if($r < 100)
                     {
                         $word .= ' ';
                     }
                     $w .= number_to_words($r);
                 }
             } 
           }
           else
           {
              if($x < 1000000)
             {
             	$w .= number_to_words(floor($x/1000)) .' thousand';
                 $r = fmod($x, 1000);
                 if($r > 0)
                 {
                     $w .= ' ';
                     if($r < 100)
                     {
                         $w .= ' ';
                     }
                     $w .= number_to_words($r);
                 }
             }
             else if($x < 1000000000)
             {
             	$w .= number_to_words(floor($x/1000000)) .' million';
                 $r = fmod($x, 1000);
                 if($r > 0)
                 {
                     $w .= ' ';
                     if($r < 100)
                     {
                         $w .= ' ';
                     }
                     $w .= number_to_words($r);
                 }
             } 
             else 
             {
                 $w .= number_to_words(floor($x/1000000000)) .' billion';
                 $r = fmod($x, 1000000);
                 if($r > 0)
                 {
                     $w .= ' ';
                     if($r < 100)
                     {
                         $word .= ' ';
                     }
                     $w .= number_to_words($r);
                 }
             }
           }
         }
     }
     return $w;
}

function currencyToText($price_total,$isIndianStandard=true)
{
  $comma_removed_price="";
  for($iii=0;$iii<strlen($price_total);$iii++)
  {
      if($price_total[$iii]==",") continue;
      $comma_removed_price=$comma_removed_price.$price_total[$iii];
  }        
  $rupees="";
  $paisa="";
  if(strpos($comma_removed_price, ".")===false)
  {
     $rupees=$comma_removed_price;
     $paisa="";
  }
  else
  {
      $arrtmp=explode(".",$comma_removed_price);
      $rupees=$arrtmp[0];
      $paisa=$arrtmp[1];
      $isPaisaZero=true;
      for($mmm=0;$mmm<strlen($paisa);$mmm++)
      {
        if($paisa[$mmm]!="0") $isPaisaZero=false;
      }
      if($isPaisaZero)
      {
        $paisa="";
      }
  }
  $price_total_rupees=(float)$rupees;
  $price_total_paisa=(float)$paisa;
      
  $descBlock=array($textcol1,$top+5,"53", $num);
  $rupeesInWords=empty($price_total_rupees)?"Zero":number_to_words($price_total_rupees,$isIndianStandard);
  $paisaInWords=empty($paisa)?null:number_to_words($price_total_paisa,$isIndianStandard);
  return array("Rupees"=>$rupeesInWords,"Paisa"=>$paisaInWords);
}

/**
/**if $userid parameter specified, return the matching user object
 * if nothing provided, returns current user
 */
function getUserObject($userid=0)
{
    $objNaanalSession=  ClsNaanalSession::getInstance();
    $loginpanel=$objNaanalSession->getLoginPanel();
    if($loginpanel=="guest") return null;
    if($userid<=0) $userid=$objNaanalSession->getLoginID();
    if($userid===0) return null;
    $objUser=ClsWrapper::getInstance($loginpanel);
    $objUser->loadObject($userid);
    return $objUser;
}

function getSessionRandomNumber($mode)
{
    $objNaanalSession=  ClsNaanalSession::getInstance();
    return $objNaanalSession->isPanelDataSet($mode)?$objNaanalSession->getPanelData($mode):  rand(9999, 99999);
}

function getModuleEncode($value)
{
    $rand=rand(99999, 9999999);
    $objNaanalSession=ClsNaanalSession::getInstance();
    $arrRand=$objNaanalSession->getPanelData("rand");
    do
    {
        $rand=rand(99999, 9999999);
    }
    while(isset($arrRand[$rand]));
    $value=serialize($value);
    //$value=ClsNaanalCrypt::getInstance($rand)->encode($value);
    $arrRand[$rand]=$value;
    $objNaanalSession->setPanelData("rand", $arrRand);
    return $rand;
}
function getModuleDecode($rand)
{
    static $arrRand=array();
    if(!isset($arrRand[$rand]))
    {
        $objNaanalSession=ClsNaanalSession::getInstance();
        $arrTmpRand=$objNaanalSession->getPanelData("rand");
        if(!isset($arrTmpRand[$rand])) return null;
        $value=$arrTmpRand[$rand];
        //$value=ClsNaanalCrypt::getInstance($arrRand[$rand])->encode($value);
        $arrRand[$rand]=unserialize($value);
        unset($arrTmpRand[$rand]);
        ClsNaanalSession::getInstance()->setPanelData("rand", $arrTmpRand);
    }
    return $arrRand[$rand];
}

function getLoginTable($loginpanel)
{
    return isset(ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["login"])?ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["login"]:$loginpanel;
}

function getRoleTable($loginpanel)
{
    return isset(ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["role"])?ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["role"]:"role";
}

function getPermissionTable($loginpanel)
{
    return isset(ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["permission"])?ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["permission"]:"permission";
}

function getRolePermissionTable($loginpanel)
{
    return isset(ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["rolepermission"])?ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["rolepermission"]:"rolepermission";
}

function getUserRoleTable($loginpanel)
{
	return isset(ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["userrole"])?ClsConfig::$CONTROL_PANEL[$loginpanel]["table"]["userrole"]:"userrole";
}

function getModuleControllerName($module)
{
    $isFrameworkModule=ClsNaanalApplication::isFrameworkModule($module);
    if($isFrameworkModule)
    {
        return "Cls".ucfirst($module);
    }
    $module_controller=getHook("module_controller_name");
    if($module_controller)
    {
        return $module_controller($module);
    }
    else
    {
        return "Cls".ucfirst($module);
    }
}

function getModuleControllerMainMethodName()
{
    $module_controller_main_method_name=getHook("module_controller_main_method_name");
    if($module_controller_main_method_name)
    {
        return $module_controller_main_method_name();
    }
    else
    {
        return "render";
    }
}

function getModuleWrapperName($module)
{
    static $arrModuleWrapperName=array();
    //if(class_exists("ClsConfig") && isset(ClsConfig::$DATABASE_WRAPPER_CLASS) && ClsConfig::$DATABASE_WRAPPER_CLASS===false) return false;
    if(!isset($arrModuleWrapperName[$module]))
    {
        $module_wrapper=getHook("module_wrapper_name");
        if($module_wrapper)
        {
            $arrModuleWrapperName[$module]=$module_wrapper($module);
        }
        else
        {
            $arrModuleWrapperName[$module]="ClsW".ucfirst($module);
        }
    }
    return $arrModuleWrapperName[$module];
}

function getUserRole($userid=null,$loginpanel=null)
{
    $loginpanel=is_null($loginpanel)?getCurrentControlPanel():$loginpanel;
    $logintable=getLoginTable($loginpanel);

    $loginWrapper="ClsW".ucfirst($logintable);
    $tblUserRole=getUserRoleTable($loginpanel);
    if(is_null($userid)) 
    {
        $user=getUserObject($loginpanel);//getCurrentUser($loginpanel);
        if(empty($user)) trace("Unexpected Request");
        $userid=$user->get_id();
    }
    $sql="select * from {$tblUserRole} where {$logintable}_id='{$userid}'";

    $pdo=ClsNaanalPDO::getNamedInstance();
    $pdo->setQuery($sql);
    $arrAssoc=$pdo->getAllAssoc();
    $arrRoleID=array();
    if($arrAssoc)
    foreach($arrAssoc as $row)
    {
        $arrRoleID[]=$row["role_id"];
    }
    return $arrRoleID;
}

/**
 * 
 * throw error if no user exist. 
 * if user exist, 
 * return false for non admin and true for admin
 * @param $id
 */
function isAdminUser($userid=0)
{
    $objUser=getUserObject($userid);
    if(!$objUser) return false;
    return $objUser->get_isadmin();
}

function isCurrentUser($userid,$loginpanel=null)
{
    list($loginpanel,$objUser)=getUser($loginpanel);
    if(!$objUser) trace("Unknown Error. Please contact your software provider");
    if($objUser->get_id()==$userid) return true;
    else return false;
}
///if $userid is 0, fetch the current user's permission
function &getUserPermission($userid=0,$loginpanel=null)
{
    static $arrUserPermission=array();
    if($userid===0)
    {
        $loginpanel=is_null($loginpanel)?getCurrentControlPanel():$loginpanel;
        $user=getUserObject();
        if(empty($user)) 
        {
            trace("Unexpected Request");  
        }
        $userid=$user->get_id();
    }
    if(isset($arrUserPermission[$userid])) return $arrUserPermission[$userid];
    $arrRoleID=getUserRole($userid);
    if(empty($arrRoleID)) 
    {
        $emptyPermission=false;
        return $emptyPermission;
    }
    $sql="select permission.id as permissionid,permissiontype.name as permissionname,feature.name as featurename from rolepermission,role,permission,permissiontype,feature where rolepermission.permission_id=permission.id and rolepermission.role_id=role.id and permission.permissiontype_id=permissiontype.id and permission.feature_id=feature.id and role_id in (".implode(",",$arrRoleID).")";
    $pdo=ClsNaanalPDO::getNamedInstance();
    $pdo->setQuery($sql);
    $arrAssoc=$pdo->getAllAssoc();
    $arrPermission=array();
    if($arrAssoc)
    foreach($arrAssoc as $row)
    {
        $arrPermission[$row["featurename"]][$row["permissionname"]]=$row;
    }
    $arrUserPermission[$userid]=$arrPermission;
    return $arrUserPermission[$userid];
}

function getDefaultDatabase()
{
    if(isset(ClsConfig::$DATABASE) && ClsConfig::$DATABASE!==false)
    {
        if(empty(ClsConfig::$DATABASE))
        {
            trace("Database not set");
        }
        else
        {
            foreach(ClsConfig::$DATABASE as $db=>$data)
            {
                if($data["default"]===true)
                {
                    return $db;
                }
            }
        }
    }
    return false;
}

function ajaxSubmit($name,$url,$urlparam,$dataType)
{
    ob_start();
?>
<script type="text/javascript" language="javascript">
var <?php echo $name; ?>;
$.ajax({
url: "<?php echo $url; ?>?<?php echo $urlparam; ?>",
dataType: "<?php echo $dataType; ?>",
success: function(data) {
	<?php echo $name; ?>=data;	
}
});
</script>
<?php
	return ob_get_clean();
}

function SplitSQL($file, $delimiter = ';')
{
    set_time_limit(0);

    if (is_file($file) === true)
    {
        $file = fopen($file, 'r');

        if (is_resource($file) === true)
        {
            $query = array();

            while (feof($file) === false)
            {
                $query[] = fgets($file);

                if (preg_match('~' . preg_quote($delimiter, '~') . '\s*$~iS', end($query)) === 1)
                {
                    $query = trim(implode('', $query));

                    if (mysql_query($query) === false)
                    {
                        //echo '<h3>ERROR: ' . $query . '</h3>' . "\n";
                    }

                    else
                    {
                        //echo '<h3>SUCCESS: ' . $query . '</h3>' . "\n";
                    }

                    while (ob_get_level() > 0)
                    {
                        ob_end_flush();
                    }

                    flush();
                }

                if (is_string($query) === true)
                {
                    $query = array();
                }
            }

            return fclose($file);
        }
    }

    return false;
}

function installSQLFile($sqlFileToExecute,$database_name, $db_user, $db_password, $hostname="localhost")
{
    /*$sqlFileToExecute = 'sqlscript.sql';
    $hostname = 'db.hostname.net';
    $db_user = 'dbuser';
    $db_password = 'dbpassword';*/
    $link = mysql_connect($hostname, $db_user, $db_password);
    if (!$link) {
      die ("MySQL Connection error");
    }

    mysql_select_db($database_name, $link) or die ("Wrong MySQL Database");

    // read the sql file
    $f = fopen($sqlFileToExecute,"r+");
    //$sqlFile = fread($f, filesize($sqlFileToExecute));
    $sqlArray = SplitSQL($sqlFileToExecute);
    foreach ($sqlArray as $stmt) {
      if (strlen($stmt)>3 && substr(ltrim($stmt),0,2)!='/*') {
        $result = mysql_query($stmt);
        if (!$result) {
          $sqlErrorCode = mysql_errno();
          $sqlErrorText = mysql_error();
          $sqlStmt = $stmt;
          break;
        }
      }
    }
    if (!isset($sqlErrorCode)) {
      return true;
    } else {
      return false;
    }
}
function getBrowserLanguage($available_languages, $default='en')
{
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

    foreach ($langs as $value){
    $choice=substr($value,0,2);
    if(in_array($choice, $available_languages)){
    return $choice;
    }
    }
    }
    return $default;
}
function getBrowserCity($ip)
{
    $default = 'UNKNOWN';
    if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
    $ip = '8.8.8.8';
    $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
    $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
    $ch = curl_init();
    $curl_opt = array(
    CURLOPT_FOLLOWLOCATION => 1,
    CURLOPT_HEADER => 0,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_USERAGENT => $curlopt_useragent,
    CURLOPT_URL => $url,
    CURLOPT_TIMEOUT => 1,
    CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
    );
    curl_setopt_array($ch, $curl_opt);
    $content = curl_exec($ch);
    if (!is_null($curl_info)) {
    $curl_info = curl_getinfo($ch);
    }
    curl_close($ch);
    if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) ) {
    $city = $regs[1];
    }
    if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) {
    $state = $regs[1];
    }
    if( $city!='' && $state!='' ){
    $location = $city . ', ' . $state;
    return $location;
    }else{
    return $default;
    }
}
?>